package com.us.usws.site.ws.resource;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.us.usws.biz.sms.SMSSenderProxy;
import com.us.usws.common.CommonUtils;
import com.us.usws.common.SiteConstants;
import com.us.usws.common.exception.SMSSendException;
import com.us.usws.model.domain.system.MobileAuth;
import com.us.usws.model.flat.system.DOUser;
import com.us.usws.service.cud.MobileAuthCUDService;
import com.us.usws.service.ro.MobileAuthROService;
import com.us.usws.service.ro.UserROService;
import com.us.usws.site.ws.entity.WSEntity;
import com.us.usws.site.ws.entity.WSEntityFactory;
import com.us.usws.support.uitls.ServiceFactory;
import com.us.usws.support.uitls.SiteWebContext;

/**
 * User webservice
 */
@Path("/authcodes")
public class AuthCodeResource {

	private static Log log = LogFactory.getFactory().getInstance(ChannelResource.class);

	private MobileAuthCUDService maS = ServiceFactory.getInstance().getService(MobileAuthCUDService.class);
	private UserROService uS = ServiceFactory.getInstance().getService(UserROService.class);
	private MobileAuthROService maRS = ServiceFactory.getInstance().getService(MobileAuthROService.class);

	@POST
	@Path("/create_code.json")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public WSEntity getActivePasswdAuthCode(@Context HttpServletRequest request, @Context HttpServletResponse response,
			@FormParam("mobile") String mobileNo) {
		String errMsg301 = "\u624b\u673a\u53f7\u7801\u683c\u5f0f\u9519\u8bef";
		String successMsg = "\u9a8c\u8bc1\u7801\u5df2\u7ecf\u53d1\u9001\u5230\u624b\u673a";

		if (!CommonUtils.isValidMobileNo(mobileNo)) {
			return getReturnEntity(errMsg301, (short) 301);
		}

		String realMobileNo = mobileNo.substring(mobileNo.length() - 11, mobileNo.length());

		//whether user exists
		DOUser dou = uS.getDOUserByLoginName(realMobileNo);
		if (dou == null || SiteConstants.STR_BOOLEAN_NO.equals(dou.getIsValid())) {
			//not actived user
			return getReturnEntity("\u7528\u6237\u672a\u6fc0\u6d3b\uff0c\u8bf7\u5148\u6fc0\u6d3b\u7528\u6237\u3002", (short) 201);
		}

		//site context
		SiteWebContext swc = new SiteWebContext(request, response);
		//gen auth
		MobileAuth ma = maS.generateNewActivateUserAuth(mobileNo, swc.getEpToken(), swc.getEpUserId());
		log.debug("{UserForgotPasswd} :: Generate MobileAuth: id=[" + ma.getId() + "], authCode=[" + ma.getAuthCode()
				+ "], where mobileNo=[" + mobileNo + "], epToken=[" + swc.getEpToken() + "], epUserid=[" + swc.getEpUserId() + "].");

		//content
		String content = "\u60a8\u597d\uff0c\u672c\u6b21\u9a8c\u8bc1\u7801\u4e3a" + ma.getAuthCode()
				+ "\u3002\u777f\u7acb\u5357\u65b9\u3002";
		try {
			SMSSenderProxy.getSMSSender().send(mobileNo, content);
		} catch (SMSSendException e) {
			log.warn("{UserForgotPasswd} :: Send SMS failed.", e);
			return getReturnEntity(errMsg301, (short) 301);
		}

		return getReturnEntity(successMsg, (short) 200);
	}

	@POST
	@Path("/check.json")
	//@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public WSEntity validateAuthCode(@Context HttpServletRequest request, @Context HttpServletResponse response,
			@FormParam("mobile") String mobileNo, @FormParam("authcode") String authCode) {
		String errMsg = "\u9a8c\u8bc1\u5931\u8d25";
		String invalidMsg = "\u9a8c\u8bc1\u7801\u65e0\u6548\u6216\u8fc7\u671f";
		short errCode = 107;
		if (!CommonUtils.isValidMobileNo(mobileNo)) {
			return getReturnEntity(errMsg, errCode);
		}

		//site context
		SiteWebContext swc = new SiteWebContext(request, response);

		MobileAuth ma = maRS.getMobileAuthByAuth(mobileNo, authCode, swc.getEpToken());
		if (ma == null) {
			return getReturnEntity(invalidMsg, errCode);
		}
		ma.setAuthedDate(new Date());
		maS.updateMobileAuth(ma);

		return getReturnEntity("\u9a8c\u8bc1\u6210\u529f", (short) 100);
	}

	/**
	 * get return entity
	 * @param msg
	 * @param code
	 * @return
	 */
	private WSEntity getReturnEntity(String msg, short code) {
		WSEntity ret = WSEntityFactory.getEmptyEntityWithRecords();
		ret.setCode(code);
		ret.setMessage(msg);
		return ret;
	}

}
